//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package mail_dao

import (
	"context"

	"atomgit.com/openlinksaas-org/api-server/dao/db_ns"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/user_mail_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type MailAccountDbItem struct {
	Account   string `bson:"_id"`
	UserId    string `bson:"userId"`
	Remark    string `bson:"remark"`
	TimeStamp int64  `bson:"timeStamp"`
}

func (item *MailAccountDbItem) ToMailAccount() *user_mail_api.MailAccount {
	return &user_mail_api.MailAccount{
		Account:   item.Account,
		UserId:    item.UserId,
		Remark:    item.Remark,
		TimeStamp: item.TimeStamp,
	}
}

type _AccountDao struct {
	mc *mongo.Collection
}

func newAccountDao(db *mongo.Database) (*_AccountDao, error) {
	mc := db.Collection(db_ns.DB_NS_MAIL + "account")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"userId", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_AccountDao{mc: mc}, nil
}

func (db *_AccountDao) Insert(ctx context.Context, dbItem *MailAccountDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_AccountDao) Exist(ctx context.Context, userId, account string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": account, "userId": userId})
	return count > 0, err
}

func (db *_AccountDao) Get(ctx context.Context, userId, account string) (*MailAccountDbItem, error) {
	retItem := &MailAccountDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": account, "userId": userId}).Decode(retItem)
	return retItem, err
}

func (db *_AccountDao) GetByAccount(ctx context.Context, account string) (*MailAccountDbItem, error) {
	retItem := &MailAccountDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": account}).Decode(retItem)
	return retItem, err
}

func (db *_AccountDao) Remove(ctx context.Context, userId, account string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": account, "userId": userId})
	return err
}

func (db *_AccountDao) UpdateRemark(ctx context.Context, userId, account, remark string, timeStamp int64) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": account, "userId": userId},
		bson.M{"$set": bson.M{"remark": remark, "timeStamp": timeStamp}})
	return err
}

func (db *_AccountDao) Count(ctx context.Context, userId string) (uint32, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"userId": userId})
	return uint32(count), err
}

func (db *_AccountDao) List(ctx context.Context, userId string) ([]*MailAccountDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"userId": userId}, options.Find().SetSort(bson.M{"timeStamp": -1}))
	if err != nil {
		return nil, err
	}
	retList := []*MailAccountDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}
